package com.wksc.framework.impexp.task;

import com.wksc.framework.impexp.bean.ImportExport;
import com.wksc.framework.impexp.constants.IEConstants;
import com.wksc.framework.impexp.log.ImpExpLog;
import com.wksc.framework.impexp.util.ClassFactory;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimerTask;

/**
 * <p>
 * CleanTimeTask.java
 * </p>
 * <p/>
 * 功能描述：定时清理类
 *
 * @creator QinJinxue
 * @date Aug 16, 2010
 */
public class CleanTimeTask extends TimerTask {

    private static final ImpExpLog log = ClassFactory.getLog(CleanTimeTask.class);

    @Override
    public void run() {
        log.info("import/export clear file on webserver and task information in database");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -(IEConstants.CLEAN_DAYS));
        Date cleanDate = cal.getTime();
        String date = df.format(cleanDate);

        try {
            // 删除日志和对应的文件
            this.cleanFile(date);
            // 删除临时文件
            this.cleanFile(IEConstants.TEM_PATH, cleanDate);
            // 删除上传错误文件
            this.cleanFile(IEConstants.ERROR_PATH, cleanDate);
            // 删除下载文件
            this.cleanFile(IEConstants.EXP_PATH, cleanDate);
            // 删除上传文件
            this.cleanFile(IEConstants.IMP_PATH, cleanDate);
        } catch (ParseException e) {
            log.error("import/export operate fail", e);
        }
    }

    /**
     * MethodDesc: 重数据库中查询出时间小于指定的时间的记录，如果有对应的文件，则一起删除
     *
     * @param cleanDate
     * @author QinJinxue
     */
    @SuppressWarnings("unchecked")
    private void cleanFile(String cleanDate) {
        List<ImportExport> logs = (List<ImportExport>) ClassFactory.getImpExpDao()
                .findClean(cleanDate);
        if (logs != null && logs.size() > 0) {
            for (ImportExport ie : logs) {
                String path = null;
                if (ie.getJobtype() == 1) { // 导出CSV格式
                    path = IEConstants.EXP_PATH + IEConstants.SEPARATOR
                            + ie.getFilename() + ".csv";
                    //FileTools.delFile(path);
                    path = IEConstants.EXP_PATH + IEConstants.SEPARATOR
                            + ie.getFilename() + ".zip";
                    //FileTools.delFile(path);
                }
                if (ie.getJobtype() == 2) { // 导出xls格式
                    path = IEConstants.EXP_PATH + IEConstants.SEPARATOR
                            + ie.getFilename() + ".xls";
                    //FileTools.delFile(path);
                }
                if (ie.getJobtype() == 3) { // 导入
                    path = IEConstants.ERROR_PATH + IEConstants.SEPARATOR
                            + ie.getFilename() + ".xls";
                    //FileTools.delFileFolder(path);
                    path = IEConstants.IMP_PATH + IEConstants.SEPARATOR
                            + ie.getFilename() + ".xls";
                    //FileTools.delFileFolder(path);
                    path = IEConstants.IMP_PATH + IEConstants.SEPARATOR
                            + ie.getFilename() + ".csv";
                    //FileTools.delFileFolder(path);
                }
            }
            ClassFactory.getImpExpDao().delete(logs);
        }
    }

    /**
     * MethodDesc: 删除指定文件夹中文件日期小于指定日期的文件和文件夹
     *
     * @param path
     * @param cleanDate
     * @throws java.text.ParseException
     * @author QinJinxue
     */
    private void cleanFile(String path, Date cleanDate) throws ParseException {
        if (true
            //FileTools.isFolderExists(path, false)
                ) {
            File file = new File(path);
            String[] fileNames = file.list();
            if (fileNames != null) {
                for (int i = 0; i < fileNames.length; i++) {
                    String fileName = fileNames[i];
                    String[] fn = fileName.split("_");
                    String date = fn[fn.length - 1];
                    date = date.split("\\.")[0];
                    SimpleDateFormat sdf = new SimpleDateFormat(
                            "yyyyMMddHHmmssSSS");
                    Date fileDate = sdf.parse(date);
                    if (fileDate.before(cleanDate)) {
                        //FileTools.delFileFolder(path + IEConstants.SEPARATOR
                        //        + fileNames[i]);
                    }
                }
            }
        }
    }
}
